package com.mingtu.guards.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.guards.R;
import com.mingtu.guards.activity.ApproveDetailsActivity;
import com.mingtu.guards.adapter.ApproveAdapter;
import com.mingtu.guards.bean.ApproveListBean;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.utils.MySPTools;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;
import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class ApproveFragment extends BaseFragment implements LazyFragmentPagerAdapter.Laziable {


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    private int currentPage = 1;
    private boolean isLoadMore = true;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private int status = 0;
    private int type = 0;
    private ApproveAdapter approveAdapter;

    public static ApproveFragment getInstance(int status,int type) {
        ApproveFragment fragment = new ApproveFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_PARAM1, status);
        bundle.putInt(ARG_PARAM2, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            status = getArguments().getInt(ARG_PARAM1);
            type = getArguments().getInt(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_approve;
    }

    @Override
    protected void initData() {

        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new SpacesItemDecoration(ItemDecorationSpaces, ItemDecorationSpaces, 0, ItemDecorationSpaces, ItemDecorationSpaces));

        approveAdapter = new ApproveAdapter();
        if(isOpenLoadAnimation){
           approveAdapter.isFirstOnly(isFirstOnly);
           approveAdapter.openLoadAnimation(animationType);
        }

        approveAdapter.setEmptyView(new EmptyDataLayout(context));
        recycler.setAdapter(approveAdapter);
        approveAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ApproveListBean.PageBean.ListBean listBean = approveAdapter.getData().get(position);
                String approveId = listBean.getTaskId();
                if (!StringUtils.isEmpty(approveId)) {
                    //从我的审批入口进入的时候，只能看待审批的详情，不能够进行审批操作
                    Bundle bundle = new Bundle();
                    bundle.putString("approveId", approveId);
                    bundle.putInt("status", status);
                    bundle.putInt("type", type);
                    IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), ApproveDetailsActivity.class, bundle);
                } else {
                    ToastUtils.showLong(getResources().getString(R.string.data_error));
                }
            }
        });
    }

    @Override
    protected void initView(View view) {

    }

    @Override
    protected void getData() {
        getApproveList(1);
        initListener();
    }


    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getApproveList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(approveAdapter.getData(), Constant.PAGE_SIZE);
                    getApproveList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }


    /**
     * 审批列表
     *
     * @param pageNum
     */
    private void getApproveList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        String beginTime = SPStaticUtils.getString(MySPTools.approveFliteBeginTime);
        String endTime = SPStaticUtils.getString(MySPTools.approveFliteEndTime);
        String keyword = SPStaticUtils.getString(MySPTools.approveSearchKey);

        HashMap<String, Object> hashMap = new HashMap<>();
        if (!StringUtils.isEmpty(beginTime)) {
            hashMap.put("beginTime", beginTime);
        }
        if (!StringUtils.isEmpty(endTime)) {
            hashMap.put("endTime", endTime);
        }
        if (!StringUtils.isEmpty(keyword)) {
            hashMap.put("applyUserName", keyword);
        }
        hashMap.put("status", status);
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);

        String str = GsonUtils.toJson(hashMap);
        String url = "";
        if (type == 0) {
            url = MyConstant.POST_APPROVE_LIST;
        } else if (type == 1) {
            url = MyConstant.POST_APPROVE_MY_APPLY_LIST;
        }


        OkGo.<String>post(url)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ApproveListBean approveListBean = new ApproveListBean();
                                approveListBean = gson.fromJson(result, ApproveListBean.class);

                                List<ApproveListBean.PageBean.ListBean> dataBeans = approveListBean.getPage().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            approveAdapter.replaceData(dataBeans);
                                        } else {
                                            approveAdapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }


    /**
     * 筛选数据 重置数据  搜索数据
     */
    public void refreshData() {
        getApproveList(1);
    }


}